#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/5/31 14:00
# @Author : 闫峰
# @File    : sign.py
import hashlib
import json
from collections import OrderedDict

class SignatureHelper:

    def __init__(self, app_secret):
        self.app_secret = app_secret

    def get_sign(self, dictionary):
        sign = []

        if dictionary is not None:
            # 对字典进行排序，Python 3.7+ 版本字典默认是有序的
            sorted_items = sorted(dictionary.items())

            # 遍历排序后的键值对
            for key, value in sorted_items:
                if value is not None and str(value) != "":
                    if key.lower() == "skustockchangelist":
                        # 假设value是一个列表或字典，需要转换为JSON字符串
                        sign.append(f"{key}{json.dumps(value)}")
                    else:
                        sign.append(f"{key}{value}")

            # 拼接最终需要加密的长字符串
            sign_str = ''.join(sign)
            sign_str = self.app_secret + sign_str + self.app_secret

            # 计算MD5值并返回
            return self.get_md5_value(sign_str)

        return ""


    def get_md5_value(self, sign):
        try:
            # 计算MD5值
            md5 = hashlib.md5()
            # md5.update(sign.encode('utf-8'))
            md5.update(sign.encode())

            # 将字节转为16进制字符串
            hex_digest = md5.hexdigest()
            # 否则返回大写
            return hex_digest.upper()
        except Exception as e:
            raise Exception("MD5 not supported", e)

if __name__ == '__main__':
    str_a ="""
    7e0a1a63542be4de3cb5488f9fba8149e8fc290access_token2nifvmpyymvypwmcms5ct4uqqudrwgpmzbcnmkt1jzjkuaf3x56iixymapp_keyf9d5cc9313893a20d5aa85c654e8f503data_typeJSONsendRequestList[{"orderSendInfoList":[{"quantity":1,"orderSn":"211-21905473070712792","parentOrderSn":"PO-211-21905452099192792","goodsId":601099548666279,"skuId":17592352673534}],"carrierId":"699272611","trackingNumber":"270324232756"}]sendType0timestamp1711009072typebg.logistics.shipment.confirmc7e0a1a63542be4de3cb5488f9fba8149e8fc290
    """
    print(SignatureHelper('1554c0c854451793629cae6a892bae2d').get_md5_value(str_a))